//
//  KWallDetailViewController.m
//  Keping
//
//  Created by Joanlove on 2018/1/11.
//  Copyright © 2018年 柯平. All rights reserved.
//

#import "KWallDetailViewController.h"
#import "KStatusData.h"
#import "KStatusTableViewCell.h"
#import <MJRefresh/MJRefresh.h>
#import "KBbsTopicsDetailRequest.h"
#import "KBbsTopicView.h"
#import "KGeneralDetailViewCell.h"
#import "KWallPersonVC.h"
#import "GPVideoCallManager.h"
#import "GPContactRequest.h"
#import "KPhotoGroupView.h"
#import "KGeneralCommentsController.h"
#import "KYPhotoBrowserController.h"

@interface KWallDetailViewController ()<UITableViewDelegate, UITableViewDataSource, KStatusTableViewCellDelegate, KGeneralDetailViewCellDelegate, UITextFieldDelegate, KStatusTableViewCellDelegate>

@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) KStatusLayout *commentLayout;
/**底部评论框*/
@property(nonatomic,weak)UITextField*commentField;
@property (nonatomic, copy) NSString *commentID;

@end

@implementation KWallDetailViewController

-(UITableView *)tableView{
    if (!_tableView) {
        UITableView* tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64.0 - 45.0) style:UITableViewStylePlain];
        tableView.tableHeaderView = [[UIView alloc]init];
        tableView.tableFooterView = [[UIView alloc]init];
        tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        tableView.delegate = self;
        tableView.dataSource = self;
        [self.view addSubview:tableView];
        _tableView = tableView;
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"Wall";
    [self.tableView registerClass:[KStatusTableViewCell class] forCellReuseIdentifier:[KStatusTableViewCell className]];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        [self getData];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page++;
        [self getData];
    }];
    
    UITextField*commentField=[[UITextField alloc]init];
    [self.view addSubview:commentField];
    commentField.placeholder=@"write a comment";
    commentField.font = kFont(14);
    commentField.layer.masksToBounds=YES;
    commentField.layer.borderColor=[UIColor colorWithHexString:@"#c1c1c1"].CGColor;
    commentField.layer.borderWidth=1;
    commentField.delegate = self;
    commentField.returnKeyType = UIReturnKeySend;
    commentField.leftView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 25, 45)];
    commentField.leftViewMode=UITextFieldViewModeAlways;
    self.commentField=commentField;
    
    [self.tableView.mj_header beginRefreshing];
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    CGFloat marginW= K_FactorW(15);
    CGFloat fieldH= K_FactorW(45.0);
    self.tableView.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight - fieldH - 64.0);
    self.commentField.frame=(CGRect){{marginW,CGRectGetMaxY(self.tableView.frame)},{kScreenWidth - 2*marginW,fieldH}};
    self.commentField.layer.cornerRadius=self.commentField.height/2;
}

-(void)getData
{
    [super getData];
    WEAKSELF
    __block KBbsGeneralDetailRequest *bbsGeneralRequest = [[KBbsGeneralDetailRequest alloc] init];
    bbsGeneralRequest.params = @{@"pageOn":@(self.page),@"pageSize":@"10",@"topicId":self.status.status.id};
    [bbsGeneralRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        NSDictionary *bbsGeneral = bbsGeneralRequest.responseObject;
        NSInteger statusGeneral = [[bbsGeneral objectForKey:@"statusCode"] integerValue];
        if (statusGeneral == 200) {
            KLog(@"bbsGeneral:%@",bbsGeneral);
            if (weakSelf.page == 1) {
                [weakSelf.data removeAllObjects];
            }
            NSArray *arr = [bbsGeneral objectForKey:@"bbsPostsViews"];
            for (NSDictionary *tmp in arr) {
                KBbsPostsViews *bbs = [KBbsPostsViews modelWithDictionary:tmp];
                [weakSelf.data addObject:bbs];
            }
        } else {
            [weakSelf showErrorText:[bbsGeneral objectForKey:@"msg"] errCode:statusGeneral];
        }
        
        if (weakSelf.page == 1) {
            [weakSelf.tableView.mj_header endRefreshing];
        } else {
            [weakSelf.tableView.mj_footer endRefreshing];
        }
        [weakSelf.tableView reloadData];
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        if (weakSelf.page == 1) {
            [weakSelf.tableView.mj_header endRefreshing];
        } else {
            [weakSelf.tableView.mj_footer endRefreshing];
        }
        [weakSelf showError:request.error];
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    return self.data.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    if (section == 0) {
        KStatusLayout *obj = self.status;
        return obj.height;
    }
    KBbsPostsViews *bbs = [self.data objectAtIndex:indexPath.row];
    return bbs.cellHeight;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    if (section == 0) {
        KStatusTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:[KStatusTableViewCell className]];
        cell.delegate = self;
        [cell setLayout:self.status];
        return cell;
    } else {
        KGeneralDetailViewCell*cell=[KGeneralDetailViewCell cellWithTableView:tableView];
        cell.delegate=self;
        KBbsPostsViews *bbs = [self.data objectAtIndex:row];
        cell.bbsPostsViews = bbs;
        return cell;
    }
    return nil;
}

- (void)updateForCommentNum {
    YYTextContainer* container = [YYTextContainer new];
    container.size = CGSizeMake(KStatusCellContentWidth-KStatusCellAvatarWH - KStatusCellPadding*3, HUGE);
    container.maximumNumberOfRows = 1;
    self.status.status.commontQty = self.status.status.commontQty  + 1;
    NSString *comments = [NSString stringWithFormat:@"%ld Comments",(long)self.status.status.commontQty];
    NSMutableAttributedString *commentcount = [[NSMutableAttributedString alloc] initWithString:comments];
    commentcount.font = SystemFont;
    commentcount.color = kDarkGrayColor;
    commentcount.backgroundColor = kClearColor;
    commentcount.lineBreakMode = NSLineBreakByCharWrapping;
    NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    style.alignment = NSTextAlignmentRight;
    [commentcount addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, 0)];
    YYTextLayout *layout = [YYTextLayout layoutWithContainer:container text:commentcount];
    self.status.commentTextLayout = layout;
    [self.tableView reloadRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark UITextFieldDelegate 协议

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    kBbsGeneralAndPost *andPost =  [[kBbsGeneralAndPost alloc] init];
    if (self.commentID) {
        andPost.params = @{@"content":textField.text,@"teachingLength":self.commentID,@"useExperience":@"dynamic"};
    } else {
        andPost.params = @{@"content":textField.text,@"topicId":self.status.status.id,@"type":@"to_topic",@"useExperience":@"dynamic"};
    }
    
    WEAKSELF
    [andPost startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        NSDictionary *dict = request.responseObject;
        NSInteger status = [[dict objectForKey:@"statusCode"] integerValue];
        [weakSelf hideHUD];
        if (status == 200) {
            weakSelf.commentField.text = nil;
            [weakSelf showSuccess:[dict objectForKey:@"msg"]];
            self.commentField.placeholder = @"write a comment";
            [weakSelf updateForCommentNum];
            [weakSelf getData];
        } else {
            [weakSelf showErrorText:[dict objectForKey:@"msg"] errCode:status];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        [weakSelf showError:request.error];
    }];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}

#pragma mark KGeneralDetailViewCellDelegate 协议
-(void)generalDetailViewCellClickComment:(NSString *)general {
    KGeneralCommentsController *vc=[KGeneralCommentsController new];
    vc.bbsPostID = general;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark KStatusTableViewCellDelegate
- (void)didClickUser:(KStatusLayout *)layout {
}
- (void)didLongClickUser:(KStatusLayout *)layout {
    WEAKSELF
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
    //姓名
    UIAlertAction *aciton1 = [UIAlertAction actionWithTitle:layout.status.realName?layout.status.realName:@"" style:UIAlertActionStyleDefault handler:nil];
    //个人信息
    UIAlertAction *aciton2 = [UIAlertAction actionWithTitle:@"View Profile" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        KWallPersonVC *person = [[KWallPersonVC alloc] initWithNibName:[KWallPersonVC className] bundle:nil];
        person.statusLayout = layout;
        [weakSelf.navigationController pushViewController:person animated:YES];
    }];
    //聊天
    UIAlertAction *aciton3 = [UIAlertAction actionWithTitle:@"Voice intercom" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[GPVideoCallManager shareManager] startCall:EMCallTypeVoice username:layout.status.phone ext:nil];
    }];
    //视频聊天
    UIAlertAction *aciton4 = [UIAlertAction actionWithTitle:@"Video intercom" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[GPVideoCallManager shareManager] startCall:EMCallTypeVideo username:layout.status.phone ext:nil];
    }];
    NSString *phone;
    if (StringNotNull(layout.status.prix)) {
        phone = [NSString stringWithFormat:@"%@ %@",layout.status.prix,layout.status.phone];
    } else {
        phone = [NSString stringWithFormat:@"%@",layout.status.phone];
    }
    //拨打电话
    UIAlertAction *aciton5 = [UIAlertAction actionWithTitle:[NSString stringWithFormat:@"Phone Call(%@)",phone] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString* str=[NSString stringWithFormat:@"telprompt://%@",phone];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }];
    //拉黑
    UIAlertAction *aciton6 = [UIAlertAction actionWithTitle:@"Block User" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSString *url = [kIMAlterUserInfoURL stringByReplacingOccurrencesOfString:@"{userId}" withString:layout.status.createBy];
        GPContactRequest *request = [[GPContactRequest alloc] initWithURL:url];
        NSString *isBlock = @"Y";
        request.isPost = YES;
        request.params = @{@"isBlock":isBlock};
        WEAKSELF
        [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
            NSDictionary *response = request.responseJSONObject;
            if ([response[@"statusCode"] integerValue] != 200) {
                [weakSelf showErrorText:response[@"msg"] errCode:[response[@"statusCode"] integerValue]];
            } else {
                [weakSelf showSuccess:response[@"msg"]];
            }
        } failure:^(__kindof KBaseRequest * _Nonnull request) {
            [weakSelf showError:request.error];
        }];
    }];
    UIAlertAction *aciton7 = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:aciton1];
    [alert addAction:aciton2];
    [alert addAction:aciton3];
    [alert addAction:aciton4];
    [alert addAction:aciton5];
    [alert addAction:aciton6];
    [alert addAction:aciton7];
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)didClickLike:(KStatusLayout *)layout {
    kBbsGeneralDetailZanRequest *zanRequest = [[kBbsGeneralDetailZanRequest alloc] init];
    zanRequest.params = @{@"entityId":layout.status.id};
    WEAKSELF
    [zanRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        NSDictionary *dict = request.responseObject;
        NSInteger status = [[dict objectForKey:@"statusCode"] integerValue];
        if (status == 200) {
            [weakSelf showText:[dict objectForKey:@"msg"]];
        } else {
            [weakSelf showText:[dict objectForKey:@"msg"]];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf showError:request.error];
    }];
}
- (void)didClickComment:(KStatusLayout *)layout {
    _commentLayout = layout;
}

- (void)didClickImages:(KStatusLayout *)layout Index:(NSInteger)index{
    
    NSMutableArray* items = [NSMutableArray new];
    NSArray* pics = layout.status.imageUrls;
    NSInteger count = pics.count;
    for (NSInteger i = 0, max = count; i < max; i ++ ) {
        NSString* url = pics[i];
        [items addObject:[KGetImageURL stringByAppendingString:url]];
    }
    [KYPhotoBrowserController showPhotoBrowserWithImages:[items copy] currentImageIndex:index delegate:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
